package com.zide.system.controller;

import com.zide.common.annotation.Log;
import com.zide.common.core.domain.CommonResult;
import com.zide.common.core.domain.PageResult;
import com.zide.common.core.domain.entity.SysRole;
import com.zide.common.core.domain.entity.SysUser;
import com.zide.common.enums.BusinessType;
import com.zide.common.utils.SecurityUtils;
import com.zide.common.utils.StringUtils;
import com.zide.common.utils.poi.ExcelUtil;
import com.zide.system.domain.dept.vo.search.SysDeptSearchVO;
import com.zide.framework.web.domain.vo.result.SysRoleResultVO;
import com.zide.system.domain.user.vo.result.SystemUserResultVO;
import com.zide.system.domain.user.vo.save.SystemUserSaveVO;
import com.zide.framework.web.mapper.SysUserSearchVO;
import com.zide.system.service.ISysDeptService;
import com.zide.system.service.ISysPostService;
import com.zide.framework.web.service.ISysRoleService;
import com.zide.system.service.ISysUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
import java.util.stream.Collectors;
import static com.zide.common.core.domain.CommonResult.*;

/**
 * 用户信息
 *
 * @author zide
 */
@Tag(name = "系统用户管理")
@RestController
@RequestMapping("/system/user")
public class SysUserController {
    @Resource
    private ISysUserService userService;

    @Resource
    private ISysRoleService roleService;

    @Resource
    private ISysDeptService deptService;

    @Resource
    private ISysPostService postService;

    @Operation(summary = "用户列表")
    @GetMapping("/list")
    public CommonResult list(SysUserSearchVO searchVO) {

        PageResult<SystemUserResultVO> list = userService.selectUserList(searchVO);
        return success(list);
    }

    @Operation(summary = "导入用户")
    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public CommonResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        List<SysUser> userList = util.importExcel(file.getInputStream());
        String operName = SecurityUtils.getUsername();
        String message = userService.importUser(userList, updateSupport, operName);
        return success(message);
    }


    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.importTemplateExcel(response, "用户数据");
    }

    @Operation(summary = "根据用户编号获取详细信息")
    @GetMapping(value = {"/", "/{userId}"})
    public CommonResult getInfo(@PathVariable(value = "userId", required = false) Long userId) {
        userService.checkUserDataScope(userId);
        CommonResult ajax = success();
        List<SysRole> roles = roleService.selectRoleAll();
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        ajax.put("posts", postService.selectPostAll());
        if (StringUtils.isNotNull(userId)) {
            SystemUserResultVO sysUser = userService.selectUserById(userId);
            ajax.put(CommonResult.DATA_TAG, sysUser);
            ajax.put("postIds", postService.selectPostListByUserId(userId));
            ajax.put("roleIds", sysUser.getRoles().stream().map(SysRole::getRoleId).collect(Collectors.toList()));
        }
        return ajax;
    }

    @Operation(summary = "新增用户")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public CommonResult add(@Validated @RequestBody SystemUserSaveVO saveVO) {
        if (!userService.checkUserNameUnique(saveVO)) {
            return error("新增用户'" + saveVO.getUsername() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(saveVO.getMobile()) && !userService.checkPhoneUnique(saveVO)) {
            return error("新增用户'" + saveVO.getUsername() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(saveVO.getEmail()) && !userService.checkEmailUnique(saveVO)) {
            return error("新增用户'" + saveVO.getUsername() + "'失败，邮箱账号已存在");
        }
        saveVO.setPassword(SecurityUtils.encryptPassword(saveVO.getPassword()));
        return getResult(userService.insertUser(saveVO));
    }

    /**
     * 修改用户
     */
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public CommonResult edit(@Validated @RequestBody SystemUserSaveVO saveVO) {
        userService.checkUserAllowed(saveVO);
        userService.checkUserDataScope(saveVO.getUserId());
        if (!userService.checkUserNameUnique(saveVO)) {
            return error("修改用户'" + saveVO.getUsername() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(saveVO.getMobile()) && !userService.checkPhoneUnique(saveVO)) {
            return error("修改用户'" + saveVO.getUsername() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(saveVO.getEmail()) && !userService.checkEmailUnique(saveVO)) {
            return error("修改用户'" + saveVO.getUsername() + "'失败，邮箱账号已存在");
        }
        return getResult(userService.updateUser(saveVO));
    }

    /**
     * 删除用户
     */
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public CommonResult remove(@PathVariable Long[] userIds) {
        if (ArrayUtils.contains(userIds, SecurityUtils.getUserId())) {
            return error("当前用户不能删除");
        }
        return getResult(userService.deleteUserByIds(userIds));
    }

    /**
     * 重置密码
     */
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public CommonResult resetPwd(@RequestBody SystemUserSaveVO saveVO) {
        userService.checkUserAllowed(saveVO);
        userService.checkUserDataScope(saveVO.getUserId());
        saveVO.setPassword(SecurityUtils.encryptPassword(saveVO.getPassword()));
        return getResult(userService.resetPwd(saveVO));
    }

    /**
     * 状态修改
     */
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public CommonResult changeStatus(@RequestBody SystemUserSaveVO saveVO) {
        userService.checkUserAllowed(saveVO);
        userService.checkUserDataScope(saveVO.getUserId());
        return getResult(userService.updateUserStatus(saveVO));
    }

    /**
     * 根据用户编号获取授权角色
     */
    @GetMapping("/authRole/{userId}")
    public CommonResult authRole(@PathVariable("userId") Long userId) {
        CommonResult ajax = success();
        SystemUserResultVO systemUserResultVO = userService.selectUserById(userId);
        List<SysRoleResultVO> sysRoleResultVOS = roleService.selectRolesByUserId(userId);
        ajax.put("user", systemUserResultVO);
        ajax.put("roles", SysUser.isAdmin(userId) ? sysRoleResultVOS : sysRoleResultVOS.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        return ajax;
    }

    /**
     * 用户授权角色
     */
    @Log(title = "用户管理", businessType = BusinessType.GRANT)
    @PutMapping("/authRole")
    public CommonResult insertAuthRole(Long userId, Long[] roleIds) {
        userService.checkUserDataScope(userId);
        userService.insertUserAuth(userId, roleIds);
        return success();
    }

    /**
     * 获取部门树列表
     */
    @GetMapping("/deptTree")
    public CommonResult deptTree(SysDeptSearchVO searchVO) {
        return success(deptService.selectDeptTreeList(searchVO));
    }
}
